package cn.wolfcode.education.util;

import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.domain.SystemLog;
import cn.wolfcode.education.mapper.SystemLogMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 用来记录当前用户的操作 时间 IP 等等
 */

public class SystemLogAspect {
    //将操做保存到表中
    @Setter
    private SystemLogMapper systemLogMapper;

    private void writeSystemLog(JoinPoint joinPoint) {
        //日志对象
        SystemLog systemLog = new SystemLog();
        //当前登陆用户
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if (employee != null) {
            systemLog.setUsername(employee.getUsername());
        }
        //时间
        systemLog.setActionTime(new Date());
        //当前切点切到的执行的方法
        String functionName = joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName();
        systemLog.setFunction(functionName);

        //参数
        String argsJsonString = null;
        try {
            argsJsonString = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        systemLog.setParams(argsJsonString);
        //设置IP
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = requestAttributes.getRequest().getRemoteAddr();
        systemLog.setIp(ip);
        //保存日志
        System.out.print(systemLogMapper.insert(systemLog));
        systemLogMapper.insert(systemLog);
    }

}
